package com.thon.controller.rest;

import java.util.Date;


import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.thon.alipay.config.AlipayConfig;
import com.thon.alipay.util.AlipaySubmit;
import com.thon.commons.utils.OrderNoGenerator;
import com.thon.dao.util.Page;
import com.thon.entity.user.FundDetail;
import com.thon.entity.user.User;
import com.thon.service.user.FundDetailService;
import com.thon.service.user.UserService;

@Controller
@RequestMapping(value = "/api/fund_detail")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class FundDetailRestController {


	@Autowired
	private FundDetailService fundDetailService;
	@Autowired
	private UserService userService;
	private static final Log log = LogFactory.getLog(FundDetailRestController.class);

	//提现申请
	@RequestMapping(value = "/getCash", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> getCash(@RequestParam("uid") Integer userId,
			@RequestParam(value = "amount", required = true)Integer amount,
			@RequestParam(value = "account", required = true)String account,
			@RequestParam(value = "realName", required = true)String realName,
			@RequestParam(value = "phone", required = true)String phone,
			@RequestParam(value = "bank", defaultValue="")String bank,
			@RequestParam(value = "payType", required = true)Integer payType){		
		
		if(fundDetailService.getFundDetail(userId)!=null)
			return new ResponseEntity("repeated", HttpStatus.OK);
		
		User user = userService.getUser(userId);
		if(user==null)
			return new ResponseEntity("no_user", HttpStatus.OK);
			
		if(user.getFund()-amount<0)
			return new ResponseEntity("no_enough_cash", HttpStatus.OK);
		
		FundDetail fundDetail = new FundDetail();
		fundDetail.setActionType(5);
		fundDetail.setAmount(amount);
		fundDetail.setProject(null);
		fundDetail.setUser(user);
		fundDetail.setProduct(null);
		fundDetail.setTradeNo(OrderNoGenerator.generator("NO"));
		fundDetail.setAccount(account);
		fundDetail.setRealName(realName);
		fundDetail.setRemainingSum(user.getFund() + amount);
		fundDetail.setPayType(payType);
		fundDetail.setBank(bank);
		fundDetail.setPhone(phone);
		
		fundDetailService.addFundDetail(fundDetail);
		return new ResponseEntity("success", HttpStatus.OK);
	}		
	
	
	// 根据用户id查询用户消费详情
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listFundDetail(
			@RequestParam(value="uid",defaultValue = "0") Integer userId,
			@RequestParam(value="action_type", defaultValue = "-1") Integer status,
			@RequestParam(value = "p", defaultValue = "1") Integer pageNo,
			@RequestParam(value = "s", defaultValue = "10") Integer pageSize,
			Model model) {

		Page<FundDetail> page = fundDetailService.findFundDetailsByUser(userId,status,
				pageNo, pageSize);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	
	// 获得提现申请
	@RequestMapping(value = "/getApplication", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listFundDetail(
				@RequestParam("uid") Integer userId) {

			FundDetail fundDetial = fundDetailService.getFundDetail(userId);
			return new ResponseEntity(fundDetial, HttpStatus.OK);
		}

	@RequestMapping(value = "/web/deposit", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> deposit(@RequestBody FundDetail newfundDetail,Model model) {
		Date date = new Date();
		User user = new User();
		FundDetail fundDetail = new FundDetail();
		Map<String, String> sParaTemp = new HashMap<String, String>();
		// 支付类型
		// 必填，不能修改
		String payment_type = "1";
		// 服务器异步通知页面路径
		// 需http://格式的完整路径，不能加?id=123这类自定义参数
		String notify_url = "http://yami.lanbaoo.com/api/alipay/async";//"http://127.0.0.1:8088/mercy/alipay/notify_url.jsp";
		// 页面跳转同步通知页面路径
		// 需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
		String return_url = "http://yami.lanbaoo.com/api/alipay/return_url";
		// 商户订单号.
		// 商户网站订单系统中唯一订单号，必填
		//String out_trade_no = date.getTime() + "";
		// 订单名称
		// 必填
		String subject = "充值积善值";
		// 防钓鱼时间戳
		// 若要使用请调用类文件submit中的query_timestamp函数
		String anti_phishing_key = "";
		// 客户端的IP地址
		// 非局域网的外网IP地址，如：221.0.0.1
		String exter_invoke_ip = "";
		
		user = userService.getUser(newfundDetail.getUser().getId());
		fundDetail.setUser(user);
		fundDetail.setActionType(3);
		fundDetail.setTradeNo(OrderNoGenerator.generator("NO"));
		fundDetail.setAmount(newfundDetail.getAmount());
		fundDetailService.addFundDetail(fundDetail);
		
		Double total_fee = (double) fundDetail.getAmount();//(fundDetail.getAmount()/100d);
		sParaTemp.put("total_fee", total_fee.toString());
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type); 
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("seller_id", AlipayConfig.seller_id);
		sParaTemp.put("out_trade_no", fundDetail.getTradeNo());
		sParaTemp.put("subject", subject);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		sParaTemp.put("key", AlipayConfig.key);
		
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		
		model.addAttribute("sHtmlText", sHtmlText);
		model.addAttribute("fundDetail", fundDetail);
		
		return new ResponseEntity(model, HttpStatus.OK);
	}
	//移动段获取订单
	@RequestMapping(value = "/deposit", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> depositFund(
			@RequestBody FundDetail newfundDetail,
			Model model) {
		User user = new User();
		FundDetail fundDetail = new FundDetail();

		user = userService.getUser(newfundDetail.getUser().getId());
		fundDetail.setUser(user);
		fundDetail.setActionType(3);
		fundDetail.setTradeNo(OrderNoGenerator.generator("NO"));
		fundDetail.setAmount(newfundDetail.getAmount());
		fundDetailService.addFundDetail(fundDetail);
		
		model.addAttribute("fundDetail", fundDetail);
		return new ResponseEntity(model, HttpStatus.OK);
	}

	

	/**
	 * 根据用户id查询某段时间内的消费详情
	 * 
	 * @param uid
	 *            用户id
	 * @param days
	 *            时间段 如:一个月内(days=30) 半个月内(days=15)
	 * @param p
	 *            页码
	 * @param s
	 *            页大小
	 * @return
	 */
	@RequestMapping(value = "/period/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listFundDetailByPeriod(
			@RequestParam("uid") int uid, @RequestParam("days") Long days,
			@RequestParam(value="p",defaultValue = "1") int p,
			@RequestParam(value="s",defaultValue = "10") int s,
			Model model) {

		Page<FundDetail> page = fundDetailService.findFundDetailsByUser(uid, p,
				s, days);
		// 消费
		int consume = 0;
		// 充值
		int abundant = 0;
		if(page.getResult()!=null)
		for (FundDetail fundDetail : page.getResult()) {
			if ((fundDetail.getActionType() == 0)||(fundDetail.getActionType() == 6)){
				consume += fundDetail.getAmount();
			}
			else if((fundDetail.getActionType()==1)||(fundDetail.getActionType()==2)||(fundDetail.getActionType()==4)){
				abundant += fundDetail.getAmount();
			}
		}
		model.addAttribute("page", page);
		model.addAttribute("consume", consume);
		model.addAttribute("abundant", abundant);
		return new ResponseEntity(model, HttpStatus.OK);
	}
	
	
}
